package com.alarm.ecp;

import com.alarm.ecp.pojo.EventPO;
import com.alarm.ecp.utils.KafkaUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.functions.PatternProcessFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * 基于【迭代条件】检测最近15分钟内IP更换次数超过3次的用户
 * 1、对于每个匹配模式，可以设置条件，判定到达的行为事件，是否能够进入到这个模式
 * 如：设置条件为只有登录成功这个行为事件，才能进入这个模式
 * 2、条件设置方法是：where()  where()的参数是IterativeCondition对象
 * 3、IterativeCondition称为迭代条件 能够设置较为复杂的条件，尤其和循环模式相结合
 */
public class IpChangeByIterative {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        DataStream<EventPO> eventStream = KafkaUtil.read(args, env);
        KeyedStream<EventPO, Integer> eventPOIntegerKeyedStream = eventStream.assignTimestampsAndWatermarks(
                WatermarkStrategy.<EventPO>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner((event, timestamp) -> event.getTimeStamp())
        ).keyBy((KeySelector<EventPO, Integer>) EventPO::getUserId);
        eventPOIntegerKeyedStream.print("数据流");
        Pattern<EventPO, EventPO> pattern = Pattern
                // 组合模式以begin开头 不设置条件，所有行为事件都可以进入这个模式
                .<EventPO>begin("ip")
                // 判断用户行为事件在15分钟内IP是否发生变化（更换IP之间可以有其他事件）
                .followedBy("next").where(new IpChangeCondition())
                // 15分钟内IP更换次数超过3次
                .timesOrMore(3)
                // 满足条件的行为事件必须在最近15分钟内
                .within(Time.seconds(900));

        PatternStream<EventPO> patternStream = CEP.pattern(eventPOIntegerKeyedStream, pattern);
        SingleOutputStreamOperator<String> process = patternStream.process(new PatternProcessFunction<EventPO, String>() {
            @Override
            public void processMatch(Map<String, List<EventPO>> map, Context context, Collector<String> collector) throws Exception {
                collector.collect("更换ip:"+map.toString());
            }
        });

        process.printToErr();
        env.execute("IpChangeByIterative");

    }
}
